package kuzmenkov.applet;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dialog;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Window;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 * The dialog that shows an image
 * @author Michael Kuzmenkov
 *
 */
public class ImageDlg extends Dialog {

	/**
	 * 
	 */
	private static final long serialVersionUID = 8189441798074794218L;
	public static final int MAX_WIDTH = 780;
	public static final int MAX_HEIGHT = 570;
	
	/**
	 * Shows in the dialog
	 */
	private Image image;
	private Component imagePanel;
	
	public ImageDlg(Window owner) {
		super(owner);
		imagePanel = new ImagePanel();
		setLayout(new BorderLayout());
		add(imagePanel);
		
		addWindowListener(new HideDlgListener());
	}
	
	
	

	public void setImage(Image image) {
		this.image = image;
		if (image!=null){
			int width = 0, height = 0; 
			int imageWidth = image.getWidth(null);
			int imageHeight = image.getHeight(null);
			double factor = 1;
			
			if (imageWidth > MAX_WIDTH && imageHeight <= MAX_HEIGHT){
				factor = (double) MAX_WIDTH/imageWidth;
				width = MAX_WIDTH;
				height = (int)(imageHeight*factor+0.5);
			} else if (imageHeight > MAX_HEIGHT && imageWidth <= MAX_WIDTH) {
				factor = (double)MAX_HEIGHT / imageHeight;
				width = (int)(imageWidth*factor+0.5);
				height = MAX_HEIGHT;
			} else if (imageWidth > MAX_WIDTH && imageHeight > MAX_HEIGHT){
				if (imageWidth - MAX_WIDTH > imageHeight - MAX_HEIGHT){
					factor = (double)MAX_WIDTH / imageWidth;
					width = MAX_WIDTH;
					height = (int)(imageHeight*factor+0.5);
				} else {
					factor = (double)MAX_HEIGHT / imageHeight;
					width = (int)(imageWidth*factor+0.5);
					height = MAX_HEIGHT;
				}
			} else if (imageWidth <= MAX_WIDTH && imageHeight <= MAX_HEIGHT) {
				width = imageWidth;
				height = imageHeight;
			} else 
				assert (false);
			
			setSize(width,height);
		}
	}

	public Image getImage() {
		return image;
	}
	
	private class ImagePanel extends Component {
		/**
		 * 
		 */
		private static final long serialVersionUID = 3009096713672381492L;

		@Override
		public void paint(Graphics g) {	
			super.paint(g);
			if (image!=null){
				Graphics2D g2d = (Graphics2D) g;
				g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, 
						RenderingHints.VALUE_INTERPOLATION_BICUBIC);
				
				
				g2d.drawImage(image, 1, 1, getWidth()-2, getHeight()-2, null);
			}
		}
	}
	
	private class  HideDlgListener extends WindowAdapter {
		@Override
		public void windowClosing(WindowEvent e) {
			setVisible(false);
		}
	}

}
